<?php
declare (strict_types = 1);

namespace app\middleware;

use app\api\extend\Common;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;

class JwtAuth extends Common
{
    /**
     * 处理请求
     *
     * @param  $request
     * @param \Closure   $next
     */
    public function handle($request, \Closure $next)
    {
        $token = $request->header('author');
        if (!$token) {
            return json(['code'=>400,'msg'=>'认证失败，缺少token！']);
        }
        try {
            $decoded = JWT::decode($token, new Key($this->key, 'HS256'));
            // 将解码后的数据放入请求中，以便后续使用
            $request->auth = (array) $decoded->data;
        } catch (ExpiredException $e) {
            return json(['code'=>400,'msg'=>'认证过期，没有权限！']);
        } catch (\Exception $e) {
            return json(['code'=>400,'msg'=>'认证无效，没有权限！']);
        }

        return $next($request);
    }

}
